<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>4_getSnapshotbeforeUpdate的使用场景</title>
    <style>
		.list{
			width: 200px;
			height: 150px;
			background-color: skyblue;
			overflow: auto;
		}
		.news{
			height: 30px;
		}
	</style>
</head>
<body>
	<!-- 准备好一个“容器” -->
	<div id="test"></div>
	
	<!-- 引入react核心库 -->
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
	<!-- 引入react-dom，用于支持react操作DOM -->
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
	<!-- 引入babel，用于将jsx转为js -->
	<script type="text/javascript" src="../js/babel.min.js"></script>

	<script type="text/babel">
        class NewsList extends React.Component{

            state = {newsArr: []}

            componentDidMount(){
                setInterval(() => {
                    const {newsArr} = this.state;

                    const news = "新闻" + (newsArr.length + 1)

                    this.setState({newsArr: [news,...newsArr]})
                }, 1000)
            }

            // 获取快照
            getSnapshotBeforeUpdate(){
                return this.refs.list.scrollHeight
            }

            componentDidUpdate(proProps, proState, height){
                this.refs.list.scrollTop += this.refs.list.scrollHeight - height;

            }


            render(){
                return (
                    <div className="list" ref="list">
                        {
                            this.state.newsArr.map((n, index) => {
                                return <div key={index} className="news">{n}</div>
                            })
                        }
                    </div>
                )
            }
        }
        ReactDOM.render(<NewsList />, document.getElementById('test'))
	</script>
</body>
</html>